<template>
  <div class="common-container">
    <el-form
      :label-position="labelPosition"
      label-width="110px"
      :model="ruleForm"
      style="width: 600px"
      :rules="rules"
      ref="ruleForm"
      size="small"
    >
      <el-form-item label="站点名称">
        <el-input
          v-model.trim="ruleForm.siteName"
          placeholder="站点名称"
          maxlength="15"
          clearable
          @keydown.native="keydown($event)"
          @input="ruleForm.siteName = ruleForm.siteName.replace(reg, '')"
        ></el-input>
      </el-form-item>
      <el-form-item label="站点logo" prop="siteLogo">
        <!-- <div
          style="
            display: flex;
            width: 140px;
            flex-direction: column;
            align-items: center;
          "
        >
          <el-upload
            :class="{ disabled: uploadDisabled }"
            :on-remove="handleRemove"
            :on-change="uploadSectionFile"
            :action="baseUrl"
            list-type="picture-card"
            accept=".jpg,.png"
            :on-preview="handlePictureCardPreview"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
            :on-success="handleSuccessFunction"
            :limit="1"
            :on-exceed="handleExceedScene"
            :file-list="fileList"
            :on-error="uploadFileError"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div
            style="
              position: relative;
              height: 140px;
              width: 140px;
              margin-top: 10px;
              display: inline-block;
            "
            @mouseenter="isHover = true"
            @mouseleave="isHover = false"
          >
            <img
              :src="ruleForm.siteLogo ? ruleForm.siteLogo : logo2"
              alt=""
              style="width: 100%; height: 100%"
              :class="{ hover: isHover && ruleForm.siteLogo }"
            />
            <i
              class="el-icon-error"
              @click="onerror"
              v-if="ruleForm.siteLogo && isHover"
              style="
                position: absolute;
                top: 2px;
                right: 2px;
                color: #7367f0;
                font-size: 15px;
                cursor: pointer;
              "
            ></i>
          </div>
        </div> -->
        <el-upload
          :class="{ disabled: uploadDisabled }"
          :on-remove="handleRemove"
          :on-change="uploadSectionFile"
          :action="baseUrl"
          list-type="picture-card"
          accept=".jpg,.png"
          :on-preview="handlePictureCardPreview"
          :headers="headers"
          :before-upload="beforeAvatarUpload"
          :on-success="handleSuccess"
          :limit="1"
          :on-exceed="handleExceedScene"
          :file-list="fileList"
          :on-error="uploadFileError"
        >
          <i class="el-icon-plus"></i>
        </el-upload>

        <!-- <el-upload
          class="upload-demo"
          :action="baseUrl"
          :headers="headers"
          :limit="1"
          accept=".jpg,.png"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          list-type="picture-card"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="ruleForm.siteLogo"
            :src="ruleForm.siteLogo"
            class="avatar"
          />
          <i class="el-icon-plus"></i>
        </el-upload> -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="大屏logo">
        <!-- <div
          style="
            display: flex;
            width: 140px;
            flex-direction: column;
            align-items: center;
          "
        >
          <div
            style="
              position: relative;
              height: 140px;
              width: 140px;
              margin-top: 10px;
              display: inline-block;
            "
            @mouseenter="isData = true"
            @mouseleave="isData = false"
          >
            <img
              :src="ruleForm.dataVLogo ? ruleForm.dataVLogo : logo2"
              alt=""
              style="width: 100%; height: 100%"
              :class="{ hover: isData && ruleForm.dataVLogo }"
            />
            <i
              class="el-icon-error"
              @click="onData"
              v-if="ruleForm.dataVLogo && isData"
              style="
                position: absolute;
                top: 2px;
                right: 2px;
                color: #7367f0;
                font-size: 15px;
                cursor: pointer;
              "
            ></i>
          </div>
          <el-upload
            class="upload-demo"
            :action="baseUrl"
            :headers="headers"
            :limit="1"
            :on-success="dataSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-button size="small" type="primary">上传图片</el-button>
          </el-upload>
        </div> -->

        <el-upload
          :class="{ disabled: uploadDisabled2 }"
          :on-remove="handleRemove2"
          :on-change="uploadSectionFile2"
          :action="baseUrl"
          list-type="picture-card"
          accept=".jpg,.png"
          :on-preview="handlePictureCardPreview2"
          :headers="headers"
          :before-upload="beforeAvatarUpload"
          :on-success="dataSuccess"
          :limit="1"
          :on-exceed="handleExceedScene"
          :file-list="fileList2"
          :on-error="uploadFileError2"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible2">
          <img width="100%" :src="dialogImageUrl2" alt="" />
        </el-dialog>
      </el-form-item>

      <!-- <el-form-item>
        <el-button type="primary" @click="zhongzhi" size="small" v-preventReClick="2000">重 置</el-button>
        <el-button type="primary" @click="onSubmit" size="small"
          >保 存</el-button
        >
      </el-form-item> -->
    </el-form>
    <!-- <el-footer>
      <div style="width: 100%; display: flex; justify-content: flex-end">
        <el-button
          type="primary"
          @click="onSubmit"
          size="small"
          style="margin-right: 20px"
          >保 存</el-button
        >
      </div>
    </el-footer> -->
    <el-button
      type="primary"
      @click="onSubmit"
      size="small"
      style="position: absolute; top: 20px; right: 20px"
      >保 存</el-button
    >
  </div>
</template>

<script>
import {
  reqGetById,
  reqOrgSuperLevelInfo,
  reqOrgByUserId,
  reqTenantEdit,
  reqOrgEdit,
  reqOrgCustomById,
} from "@api/api.js";
import { mapState, mapMutations } from "vuex";
import { validMobile } from "@utils/validate";
import asc from "@utils/asc.js"; //加密解密

export default {
  name: "site",
  components: {},
  data() {
    return {
      // 禁止输入表情包
      reg: /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi,
      baseUrl: "",
      labelPosition: "right",
      ruleForm: {
        siteName: "",
        siteLogo: "",
        dataVLogo: "",
      },
      dialogImageUrl: "",
      dialogVisible: false,
      headers: {
        token: asc.decrypt(sessionStorage.getItem("token")),
      },
      rules: {
        name: [{ required: true, message: "请输入租户名称", trigger: "blur" }],
        siteName: [
          { required: true, message: "请输入站点名称", trigger: "blur" },
        ],
        username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: validMobile,
          },
        ],
      },
      name: "",
      logo: "",
      isHover: false,
      isData: false,
      logo2: require("@assets/images/logo4.png"),
      fileList: [],
      uploadDisabled: false, //加号默认显示

      // 大屏logo
      uploadDisabled2: false, //加号默认显示
      dialogVisible2: false,
      fileList2: [],
      dataVLogo: "",
      dialogImageUrl2: "",
      orgInfo: {},
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  watch: {},
  methods: {
    ...mapMutations(["saveSiteName", "saveSiteLogo", "saveDataVLogo"]),
    // 禁止输入空格
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    onerror() {
      this.ruleForm.siteLogo = "";
    },
    onData() {
      this.ruleForm.dataVLogo = "";
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      let isJPG = true;
      let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        this.$modal.notifyWarning("图片只能是 jpg/png 格式!");
        isJPG = false;
        return isJPG;
      } else if (!isLt) {
        this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
        isJPG = false;
      }
      return isJPG;
    },
    async zhongzhi() {
      this.$confirm("确定要重置站点设置吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.ruleForm.siteLogo = "";
          this.ruleForm.siteName = "";
          const res = await reqTenantEdit(this.ruleForm);
          // console.log(res);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("重置成功");
          this.saveSiteName(""); //站点名称
          this.saveSiteLogo(""); //站点logo
          this.saveDataVLogo("");
          this.name = this.ruleForm.siteName;
          this.logo = this.ruleForm.siteLogo;
        })
        .catch(() => {});
    },
    // 上传成功
    handleSuccess(response, file, fileList) {
      // console.log(e.data.url);
      // this.ruleForm.siteLogo = e.data.url;
      this.ruleForm.siteLogo = file.response.data.url;
      // this.fileList = [file]; // 手动同步文件列表状态
    },
    //上传失败
    uploadFileError(err, file, fileList) {
      this.uploadDisabled = false;
    },
    uploadSectionFile(file, fileList) {
      if (fileList.length >= 1) {
        this.uploadDisabled = true; //隐藏加号
      }
    },
    // 文件超出个数限制时的钩子
    handleExceedScene() {
      this.$modal.notifyWarning(`产品图片只能上传一张图片`);
    },
    handlePictureCardPreview(file) {
      console.log(file, "file");
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // //删除照片
    handleRemove(file) {
      this.ruleForm.siteLogo = "";
      setTimeout(() => {
        this.uploadDisabled = false;
      }, 1000);
    },

    // 大屏logo
    dataSuccess(e) {
      this.ruleForm.dataVLogo = e.data.url;
    },
    //上传失败
    uploadFileError2(err, file, fileList) {
      this.uploadDisabled2 = false;
    },
    uploadSectionFile2(file, fileList) {
      if (fileList.length >= 1) {
        this.uploadDisabled2 = true; //隐藏加号
      }
    },
    handlePictureCardPreview2(file) {
      console.log(file, "file");
      this.dialogImageUrl2 = file.url;
      this.dialogVisible2 = true;
    },
    // //删除照片
    handleRemove2(file) {
      this.ruleForm.dataVLogo = "";
      setTimeout(() => {
        this.uploadDisabled2 = false;
      }, 1000);
    },

    async getList() {
      const res = await reqGetById(this.user.tenantId);
      this.ruleForm = res.data.row;
      this.ruleForm.siteName = this.ruleForm.siteName
        ? this.ruleForm.siteName
        : "精卫安";
      // 防止没修改无限点保存
      this.name = res.data.row.siteName || "";
      if (res.data.row.siteLogo) {
        this.ruleForm.siteLogo = this.logo = res.data.row.siteLogo || "";
        this.fileList = [{ name: "", url: res.data.row.siteLogo }];
        this.uploadDisabled = true;
      } else {
        this.ruleForm.siteLogo = this.logo = "";
        this.fileList = [];
        this.uploadDisabled = false;
      }

      if (res.data.row.dataVLogo) {
        this.ruleForm.dataVLogo = this.dataVLogo = res.data.row.dataVLogo || "";
        this.fileList2 = [{ name: "", url: res.data.row.dataVLogo }];
        this.uploadDisabled2 = true;
      } else {
        this.ruleForm.dataVLogo = this.dataVLogo = "";
        this.fileList2 = [];
        this.uploadDisabled2 = false;
      }
    },
    // 获取用户所在机构
    async getOrgByUserId() {
      const res = await reqOrgByUserId(this.user.userId);
      console.log("查询上级组织机构信息", res);
      if (res.code !== 20000) {
        this.name = "";
        this.logo = "";
        this.dataVLogo = "";
        this.$modal.notifyWarning(res.message);
        return;
      }
      this.orgInfo = res.data.rows[0];
      this.getOrgSuperLevelInfo(res.data.rows[0].id);
    },

    async getOrgSuperLevelInfo(orgId) {
      const res = await reqOrgSuperLevelInfo(orgId);
      // 防止没修改无限点保存
      this.ruleForm.siteName = this.name = res.data.row.customName || "";
      if (res.data.row.customLogo) {
        this.ruleForm.siteLogo = this.logo = res.data.row.customLogo || "";
        this.fileList = [{ name: "", url: res.data.row.customLogo }];
        this.uploadDisabled = true;
      } else {
        this.ruleForm.siteLogo = this.logo = "";
        this.fileList = [];
        this.uploadDisabled = false;
      }

      if (res.data.row.customVLogo) {
        this.ruleForm.dataVLogo = this.dataVLogo =
          res.data.row.customVLogo || "";
        this.fileList2 = [{ name: "", url: res.data.row.customVLogo }];
        this.uploadDisabled2 = true;
      } else {
        this.ruleForm.dataVLogo = this.dataVLogo = "";
        this.fileList2 = [];
        this.uploadDisabled2 = false;
      }
    },

    // 提交
    onSubmit() {
      this.$notify.closeAll();
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (
            this.name == this.ruleForm.siteName &&
            this.logo == this.ruleForm.siteLogo &&
            this.dataVLogo == this.ruleForm.dataVLogo
          )
            return this.$modal.notifyWarning("请修改后再保存");
          if (this.user.roleName == "TENANT_ADMIN") {
            this.tenantChange();
          } else if (
            this.user.roleName == "ORG_ADMIN" ||
            this.user.roleName == "UNIT_ADMIN"
          ) {
            this.unitChange();
          }
        }
      });
    },

    // 租户内容修改
    async tenantChange() {
      const res = await reqTenantEdit(this.ruleForm);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("更新成功");
      this.saveSiteName(this.ruleForm.siteName); //站点名称
      this.saveSiteLogo(this.ruleForm.siteLogo); //站点logo
      this.saveDataVLogo(this.ruleForm.dataVLogo); //大屏logo
      this.name = this.ruleForm.siteName;
      this.logo = this.ruleForm.siteLogo;
      this.dataVLogo = this.ruleForm.dataVLogo;
    },

    // 单位内容修改
    async unitChange() {
      let params = {
        id: this.orgInfo.id,
        orgName: this.orgInfo.orgName,
        province: this.orgInfo.province,
        city: this.orgInfo.city,
        area: this.orgInfo.area,
        address: this.orgInfo.address,
        customName: this.ruleForm.siteName,
        customLogo: this.ruleForm.siteLogo,
        customVLogo: this.ruleForm.dataVLogo,
      };
      const res = await reqOrgEdit(params);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("更新成功");
      if (
        this.ruleForm.siteName &&
        this.ruleForm.siteLogo &&
        this.ruleForm.dataVLogo
      ) {
        this.saveSiteName(this.ruleForm.siteName); //站点名称
        this.saveSiteLogo(this.ruleForm.siteLogo); //站点logo
        this.saveDataVLogo(this.ruleForm.dataVLogo); //大屏logo
      } else {
        this.getOrgCustomInfo();
      }
      this.name = this.ruleForm.siteName;
      this.logo = this.ruleForm.siteLogo;
      this.dataVLogo = this.ruleForm.dataVLogo;
    },
    // async getOrgByUserId() {
    //   const res = await reqOrgByUserId(this.user.userId);
    //   if (res.code !== 20000) {
    //     this.$modal.notifyWarning(res.message);
    //     return;
    //   }
    //   this.orgInfo = res.data.rows[0];
    //   this.getOrgCustomInfo(res.data.rows[0].id);
    // },

    async getOrgCustomInfo(orgId) {
      const res = await reqOrgCustomById(this.orgInfo.id);
      if (!this.ruleForm.siteName) {
        this.saveSiteName(res.data.row.customName || ""); //站点名称
      } else {
        this.saveSiteName(this.ruleForm.siteName); //站点名称
      }
      if (!this.ruleForm.siteLogo) {
        this.saveSiteLogo(res.data.row.customLogo || ""); //站点logo
      } else {
        this.saveSiteLogo(this.ruleForm.siteLogo); //站点名称
      }

      if (!this.ruleForm.dataVLogo) {
        this.saveDataVLogo(res.data.row.customVLogo || ""); //站点logo
      } else {
        this.saveDataVLogo(this.ruleForm.dataVLogo); //站点名称
      }
      // this.saveSiteName(res.data.row.customName || ""); //站点名称
      // this.saveSiteLogo(res.data.row.customLogo || ""); //站点logo
      // this.saveDataVLogo(res.data.row.customVLogo || ""); //站点logo
    },
  },
  created() {
    if (this.user.roleName == "TENANT_ADMIN") {
      this.getList();
    } else if (
      this.user.roleName == "ORG_ADMIN" ||
      this.user.roleName == "UNIT_ADMIN"
    ) {
      this.getOrgByUserId();
    }
    this.baseUrl = `${this.$baseURL_copy}file/upload`;
  },
};
</script>

<style lang="less" scoped>
@import url("~@views/style/tablePage.less");

.common-container {
  padding-left: 20px;
  padding-top: 20px;
  box-sizing: border-box;
  overflow: auto;
  position: relative;
}

::v-deep .el-form-item {
  margin-bottom: 16px !important;
}

.enterprise {
  padding-top: 30px;
  padding-left: 30px;
}

.el-form-item {
  margin-bottom: 15px;
}

// ::v-deep .el-upload-list {
//   display: none !important;
// }

.hover {
  opacity: 0.3;
}

.upload-demo {
  margin-top: 10px;
}

::v-deep .el-upload--picture-card {
  background-color: transparent !important;
}

// 隐藏加号
::v-deep .disabled .el-upload--picture-card {
  display: none !important;
}

::v-deep .el_dialog .el-dialog__body {
  margin-bottom: 20px;
}
</style>
